package com.wsc.springbootmultidevdemo.msg;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 从 MQ 接收消息
 */
@Slf4j
public class Receive {

    //队列名称
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        System.out.println("Consumer is ready for receive message from queue");

/*
        DeliverCallback deliverCallback = (consumerTag,delivery) ->{
            String message = new String(delivery.getBody(),"UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumerTag ->{});*/

        //new 一个消费者
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                log.info("Receive message:"+message);
            }
        };
        //param2:应答模式：true：自动应答，即消费者获取到消息，该消息就会从队列中删除掉
        //false:手动应答，当从队列中取出消息后，需手动调用方法应答，如果没有应答，该消息还会再放进队列中，就会出现该消息一直没有被消费掉的现象
        channel.basicConsume(QUEUE_NAME,true,consumer);

    }

}
